package com.yangyang.androidconnect.util;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.*;
import java.util.stream.*;

public class FileTraverserNIO {
    public static List<Path> listFilesSortedByCreationTime(String... directories) throws IOException {
        List<Path> allFiles = new ArrayList<>();

        for (String dir : directories) {
            Path path = Paths.get(dir);
            if (Files.exists(path)) {
                try (Stream<Path> stream = Files.walk(path)) {
                    stream.filter(Files::isRegularFile)
                            .filter(p -> !isHiddenPath(p))
                            .forEach(allFiles::add);
                }
            }
        }

        // 按最后修改时间排序（最新的在前）
        allFiles.sort((p1, p2) -> {
            try {
                return Files.getLastModifiedTime(p2).compareTo(Files.getLastModifiedTime(p1));
            } catch (IOException e) {
                return 0;
            }
        });

        return allFiles;
    }

    private static boolean isHiddenPath(Path path) {
        // 检查文件名是否以.开头
        if (path.getFileName().toString().startsWith(".")) {
            return true;
        }

        // 检查所有父目录是否以.开头
        Path parent = path.getParent();
        while (parent != null) {
            if (parent.getFileName() != null && parent.getFileName().toString().startsWith(".")) {
                return true;
            }
            parent = parent.getParent();
        }

        return false;
    }
}